<?php

namespace App\Http\Requests;

use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class MenuRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $menu = optional($this->route('menu'));

        $rules = [
            'parent_id' => [
                'bail',
                'required',
                Rule::exists('menus', 'id')->where(function (Builder $query) use ($menu) {
                    $query->where('id', '<>', $menu->id);
                }),
            ],
            'title'     => 'bail|required|max:50',
            'icon'      => 'max:255',
        ];

        if ($this->parent_id === 0) {
            $rules['parent_id'] = 'required';
        }

        if ($this->url) {
            $rules['url'] = 'bail|max:255|unique:menus,url,'.(int) $menu->id;
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'parent_id.*' => ':attribute 无效',
        ];
    }

    public function attributes()
    {
        return [
            'parent_id' => '父级菜单',
            'title'     => '标题',
            'url'       => '地址',
            'icon'      => '图标',
        ];
    }
}
